package com.gaojice.server.http.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import com.gaojice.server.constants.Constants;
import com.gaojice.server.http.model.Request;
import com.gaojice.server.http.model.RequestHeader;

public class RequestService {

	public Request parseFromString(String src) {
		String[] lines = src.split("\n");
		Request request = new Request();
		RequestHeader header = new RequestHeader();
		header.setMethod(lines[0].split(" ")[0]);
		header.setRequestPath(lines[0].split(" ")[1]);
		header.setProtocal(lines[0].split(" ")[2]);
		for (String line : lines) {
			if (line.contains("Content-Type")) {
				header.setContentType(line.split(": ")[1]);
			}
			if (line.contains("Content-Length")) {
				header.setContentLength(line.split(": ")[1]);
			}
			if (line.contains("Accept:")) {
				header.setAccept(line.split(": ")[1]);
			}
			if (line.contains("Accept-Language:")) {
				header.setAcceptLanguage(line.split(": ")[1]);
			}
			if (line.contains("Accept-Encoding:")) {
				header.setAcceptEncoding(line.split(": ")[1]);
			}
			if (line.contains("User-Agent:")) {
				header.setUserAgent(line.split(": ")[1]);
			}
			if (line.contains("Host:")) {
				header.setHost(line.split(": ")[1]);
			}
			if (line.contains("Host:")) {
				header.setConnection(line.split(": ")[1]);
			}

		}
		request.setHeader(header);
		return request;
	}

	// public Request getRequestFromSocket(Socket socket) throws IOException {
	// BufferedReader bufferedReader = new BufferedReader(
	// new InputStreamReader(socket.getInputStream()));
	// String line = null;
	// while ((line = bufferedReader.readLine()) != null) {
	// System.out.println(line);
	// }
	//
	// Request request = new Request();
	// request.setHeader(new RequestHeader());
	// request.getHeader().setRequestPath("");
	// return request;
	// }

	public Request getRequestFromSocket(Socket socket) throws IOException {
		InputStream inputStream = socket.getInputStream();
		StringBuffer headerBuffer = new StringBuffer();
		int data = -1;
		while ((data = inputStream.read()) != -1) {
			char ch = (char) data;
			headerBuffer.append((char) data);
			if (ch == 10) {
				if (headerBuffer.substring(headerBuffer.length() - 4).equals(
						Constants.BLANK_LINE)) {
					break;
				}
			}
		}
		System.out.println(headerBuffer.toString());
		if (headerBuffer.indexOf("multipart/form-data") > 0) {
			long readed = 0;
			while ((data = inputStream.read()) != -1) {
				readed++;
				char ch = (char) data;
				headerBuffer.append((char) data);
				if (ch == 10) {
					if (headerBuffer.substring(headerBuffer.length() - 4)
							.equals(Constants.BLANK_LINE)) {
						break;
					}
				}
			}
			long contentLength = getContentLength(headerBuffer.toString());
			long boundaryLength = getBoundaryLength(headerBuffer.toString());
			long start = System.currentTimeMillis();
			String filename = headerBuffer.substring(headerBuffer
					.indexOf("filename=\"") + 10, headerBuffer
					.lastIndexOf("\""));
			if(filename.contains("\\")){
				filename=filename.substring(filename.lastIndexOf("\\")+1);
			}
			File file = new File(Constants.ROOT_DIR
					+ "/"
					+ filename);
			FileOutputStream fileWriter = new FileOutputStream(file);
			int tempSize = 1024 * 10;
			byte[] temp = new byte[tempSize];
			long fileByteCount = contentLength - readed - (boundaryLength + 7);
			long fileByteLoaded = 0;
			if (fileByteCount < tempSize) {
				temp = new byte[(int) fileByteCount];
				inputStream.read(temp, 0, (int) fileByteCount);
				fileWriter.write(temp);
			} else {
				while (fileByteLoaded <= fileByteCount) {
					inputStream.read(temp, 0, tempSize);
					fileByteLoaded += temp.length;
					fileWriter.write(temp);
					if ((fileByteCount - fileByteLoaded) < tempSize) {
						temp = new byte[(int) (fileByteCount - fileByteLoaded)];
						inputStream.read(temp, 0,
								(int) (fileByteCount - fileByteLoaded));
						fileWriter.write(temp);
						break;
					}
				}

			}
			System.out.println("speed: " + (fileByteCount)
					/ (System.currentTimeMillis() - start) + "byte/ms");
			fileWriter.flush();
			fileWriter.close();
		}
		return parseFromString(headerBuffer.toString());
	}

	private long getBoundaryLength(String string) {
		String[] lines = string.split("\r\n");
		for (String str : lines) {
			if (str.contains("boundary")) {
				String lengthStr = str.split("=")[1];
				return Long.valueOf(lengthStr.length());
			}
		}
		return Long.valueOf(0);
	}

	private long getContentLength(String src) {
		String[] lines = src.split("\r\n");
		for (String string : lines) {
			if (string.contains("Content-Length")) {
				String lengthStr = string.split(": ")[1];
				return Long.valueOf(lengthStr);
			}
		}
		return Long.valueOf(0);
	}
}
